import { Promise } from 'core-js'

const getDefaultState = () => {
  if (!sessionStorage.getItem('order-pageNum')) {
    sessionStorage.setItem('order-pageNum', 1)
  }
  return {
    pageNum: Number.parseInt(sessionStorage.getItem('order-pageNum')),
    creatOrderTime: []
  }
}

const state = { ...getDefaultState() }

const mutations = {
  INIT: (state) => {
    state = { ...getDefaultState() }
  },
  INIT_CTEAT_TIME: (state) => {
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 1000 * 60 * 60 * 24 * 3)
    state.creatOrderTime.push(start)
    state.creatOrderTime.push(end)
  },
  SET_PAGE: (state, pageNum) => {
    state.pageNum = pageNum
  },
  SET_CTEAT_TIME: (state, creatTime) => {
    state.creatOrderTime = creatTime
  }
}

const actions = {
  init({ commit }) {
    commit('INIT')
  },
  setPageNum({ commit }, pageNum) {
    commit('SET_PAGE', pageNum)
    sessionStorage.setItem('order-pageNum', pageNum)
  },
  setCreatOrderTime({ commit }, creatTime) {
    if (creatTime) {
      commit('SET_CTEAT_TIME', creatTime)
    }
  },
  getCreatOrderTime({ commit }) {
    return new Promise((resolve, reject) => {
      if (state.creatOrderTime.length === 2) {
        resolve(state.creatOrderTime)
      } else {
        commit('INIT_CTEAT_TIME')
        resolve(state.creatOrderTime)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

